package org.popupcommunication.service.impl;

import java.util.List;

import org.popupcommunication.dao.ResponseForumDAO;
import org.popupcommunication.dao.SujetForumDAO;
import org.popupcommunication.dao.UserDAO;
import org.popupcommunication.model.ResponseForum;
import org.popupcommunication.model.SujetForum;
import org.popupcommunication.model.User;
import org.popupcommunication.service.ResponseForumManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;

public class ResponseForumManagerBean  implements ResponseForumManager{
	private ResponseForumDAO responseForumRepository;
	@Autowired
	UserDAO userRepository;
	@Autowired
	SujetForumDAO sujetForumRepository;	
	
	public ResponseForumDAO getResponseForumRepository() {
		return responseForumRepository;
	}

	public void setResponseForumRepository(ResponseForumDAO responseForumRepository) {
		this.responseForumRepository = responseForumRepository;
	}

	public UserDAO getUserRepository() {
		return userRepository;
	}

	public void setUserRepository(UserDAO userRepository) {
		this.userRepository = userRepository;
	}

	public SujetForumDAO getSujetForumRepository() {
		return sujetForumRepository;
	}

	public void setSujetForumRepository(SujetForumDAO sujetForumRepository) {
		this.sujetForumRepository = sujetForumRepository;
	}

	@Override
	public List<ResponseForum> getListResponses(SujetForum s) {
		return responseForumRepository.getListResponses(s);
	}

	@Override
	public boolean add(ResponseForum r, Errors errors) {
        boolean valid = !errors.hasErrors();
        if (valid){
        	User u = userRepository.findById(r.getPostedBy().getIdUser());
        	SujetForum s  = sujetForumRepository.findById(r.getSujet().getIdSujet());
//        	System.out.println("on tente de persister");
//        	System.out.println("**************************");
//        	System.out.println("reponse to string "+r);
//        	System.out.println("reponse user id "+r.getPostedBy().getIdUser());

        	u.addReponse(r);  
        	s.addReponse(r);
        	r.setPostedBy(u);
        	r.setSujet(s);
        	if ((u !=null) && (s!=null))
        		{
        		responseForumRepository.add(r);
        		}
        	else
        		System.out.println("pas fait le persist");  	
        }      
		return valid;
	}

	@Override
	public void deleteReponse(ResponseForum r) {
		responseForumRepository.delete(r);
		
	}

	@Override
	public ResponseForum findById(Integer i) {
		return responseForumRepository.findById(i);
	}

	@Override
	public void updateSujet(ResponseForum r) {
		responseForumRepository.save(r);	
	}

}
